package org.miaosha.controller;

import org.miaosha.model.GoodsInfoView;
import org.miaosha.model.MiaoshaOrder;
import org.miaosha.model.MiaoshaUser;
import org.miaosha.model.OrderInfo;
import org.miaosha.result.CodeMsg;
import org.miaosha.service.GoodsService;
import org.miaosha.service.MiaoshaService;
import org.miaosha.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author Wrb
 * @date 2019/7/26 17:13
 */
@Controller
@RequestMapping("/miaosha")
public class MiaoshaController {

	private final static Logger log = LoggerFactory.getLogger(MiaoshaController.class);

	@Autowired
	private GoodsService goodsService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private MiaoshaService miaoshaService;

	@RequestMapping("/do_miaosha")
	public String miaosha(Model model, MiaoshaUser user, @RequestParam("goodsId") Long goodsId) {
		model.addAttribute("user", user);
		if (user == null) {
			return "login";
		}
		//判断库存
		GoodsInfoView goods = goodsService.getGoodsInfoById(goodsId);
		int stock = goods.getGoodsStock();
		if (stock <= 0) {
			model.addAttribute("errormsg", CodeMsg.MIAO_SHA_OVER);
			return "miaosha_fail";
		}
		//判断是否已经秒杀到了
		MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdAndGoodsId(user.getId(), goodsId);
		if (order != null) {
			model.addAttribute("errmsg", CodeMsg.REPEAT_MIAO);
			return "miaosha_fail";
		}
		//减库存 下订单 写入秒杀订单
		OrderInfo orderInfo = miaoshaService.miaosha(user, goods);
		model.addAttribute("orderInfo", orderInfo);
		model.addAttribute("goods", goods);
		return "order_detail";
	}
}
